# @Author     ：SEED
# @DateTime   ：2019-08-20  19:36 
# @FileName   ：dict.py
from assets.models import Dict
from rest_framework.generics import ListAPIView
from assets.serializers.dict_serializer import DictSerializer, DictTreeSerializer
from rest_framework import viewsets
from rest_framework.response import Response
from common.custom import CustomPagination, RbacPermission
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from common.custom import TreeAPIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


class DictViewSet(viewsets.ModelViewSet):
    """
    数据字典
    """
    perms_map = ({'*': 'admin'}, {'*': 'dict_all'}, {'get': 'dict_list'}, {'post': 'dict_create'}, {'put': 'dict_edit'},
                 {'delete': 'dict_delete'})
    queryset = Dict.objects.all()
    serializer_class = DictSerializer
    pagination_class = CustomPagination
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    search_fields = ('key', 'value')
    ordering_fields = ('id',)
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (RbacPermission,)

    def list(self, request, *args, **kwargs):
        """
        :param request:list
        :param args:树结构
        :param kwargs:
        :return:
        """
        keys = self.request.query_params.get('key', '').replace(',', ' ').split()
        print(keys)
        if not keys:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            serializer = self.get_serializer(queryset, many=True)
            tree_dict = {}
            tree_data = []
            try:
                for item in serializer.data:
                    tree_dict[item['id']] = item
                for i in tree_dict:
                    if tree_dict[i]['pid']:
                        pid = tree_dict[i]['pid']
                        parent = tree_dict[pid]
                        parent.setdefault('children', []).append(tree_dict[i])
                    else:
                        tree_data.append(tree_dict[i])
                results = tree_data
            except KeyError:
                results = serializer.data
            if page is not None:
                return self.get_paginated_response(results)
        else:
            results = []
            for key in keys:
                queryset = Dict.objects.filter(pid__key=key)
                serializer = self.get_serializer(queryset, many=True)
                results.append({key: serializer.data})
        return Response(results)


class GetDictByKey(ListAPIView):
    serializer_class = DictSerializer

    def get(self, request, *args, **kwargs):
        # KEY结构为 key=['TYPE1','TYPE2']
        keys = self.request.query_params.get('key', '').replace(',', ' ').split()
        results = []
        for key in keys:
            queryset = Dict.objects.filter(pid__key=key)
            serializer = self.get_serializer(queryset, many=True)
            results.append({key: serializer.data})
        return Response(results)


class DictTreeView(TreeAPIView):
    """
    字典树
    """
    queryset = Dict.objects.all()
    serializer_class = DictTreeSerializer
    # print(serializer_class)
